package edu.scu.declaresys.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import edu.scu.declaresys.config.Configs;
import edu.scu.declaresys.dao.DAOFactory;
import edu.scu.declaresys.dao.intr.IAreaDAO;
import edu.scu.declaresys.dao.intr.IUserDAO;
import edu.scu.declaresys.dao.util.Depth;
import edu.scu.declaresys.exception.ExecuteException;
import edu.scu.declaresys.util.PageList;
import edu.scu.declaresys.vo.User;

/**
 * 
 * @author: zt
 * @since : 2013-7-5
 */
public class UserDAOImpl extends GeneralDAOImpl<User> implements IUserDAO
{
	
	public UserDAOImpl()
	{
		super(User.class);
	}

	@Override
	protected void fillReference(User vo, int depth) throws ExecuteException
	{
		IAreaDAO areaDao = DAOFactory.createAreaDAO();
		vo.setCity(areaDao.findById(vo.getCityId(), depth - 1));
		vo.setCounty(areaDao.findById(vo.getCountyId(), depth - 1));
		vo.setProvince(areaDao.findById(vo.getProvinceId(), depth - 1));
		
		return ;
	}

	@Override
	public User findByNameAndPswd(String name, String pswd) throws ExecuteException
	{
		User vo = new User();
		vo.setLoginName(name);
		vo.setPswd(pswd);
		return super.findByExampleUnique(vo, Depth.FIVE);
	}

	@Override
	public PageList<User> findUserList(Integer areaCityId,Integer areaCountyId, String userName, Integer role,
			int depth,
			Integer pageNum, Integer amtPerPage, String orderColumn,
			Boolean isAsc) throws ExecuteException
	{
		PageList<User> voLst = new PageList<User>();
		try
		{
			Session session = getSession();
			Criteria criteria = session.createCriteria(clzz);
			
			if(areaCityId != null)
			{
				criteria.add(Restrictions.eq(User.T_CITY_ID, areaCityId));
			}
			if(areaCountyId != null)
			{
				criteria.add(Restrictions.eq(User.T_COUNTY_ID, areaCountyId));
			}
			if(userName != null)
			{
				criteria.add(Restrictions.like(User.T_LOGIN_NAME, userName, MatchMode.ANYWHERE));
			}
			if(role != null)
			{
				criteria.add(Restrictions.eq(User.T_ROLE, role));
			}
			dealPageAndOrder(criteria, depth, pageNum, amtPerPage, orderColumn, isAsc, voLst);
		}
		catch(RuntimeException re)
		{
			log.error("findUserList failed", re);
			throw new ExecuteException(Configs.isDebug ? re.getMessage() : "");
		}
		finally
		{
			closeSession();
		}
		return voLst;
	}


	
}
